package com.example.addemoone.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.addemoone.R

class MyRecyclerAdapter(private val items: List<String>): RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder>() {
    /**
     * 创建新的ViewHolder实例，该方法在RecyclerView首次显示时调用
     * @param parent 父布局
     * @param viewType 布局类型
     * @return ViewHolder实例
     */
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): MyViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.recycler_view_item, parent, false)
        return MyViewHolder(view)
    }

    /**
     * 绑定数据到ViewHolder中，该方法在RecyclerView滚动时调用
     * @param holder ViewHolder实例
     * @param position 当前项的索引
     */
    override fun onBindViewHolder(
        holder: MyViewHolder,
        position: Int
    ) {
        holder.textView.text = items[position]
    }

    override fun getItemCount(): Int {
        return items.size
    }

    /**
     * 用于缓存视图中的控件
     */
    class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
        val textView: TextView = itemView.findViewById<TextView>(R.id.recyclerItem)
    }
}